﻿using LambdaToSql.FrameWork;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Linq.Expressions;
using System.Diagnostics;
using Newtonsoft.Json;

namespace LambdaToSql.Realization
{
    internal class Deleteable<T> : LambdaToSql.Interface.IDeleteable<T> where T : class, new()
    {
        public virtual LambdaToSql.EntityModel.DbContext Context { get; set; }

        internal LambdaToSql.EntityModel.DeleteEntity<T> Entity { get; set; }
         
        public Deleteable(LambdaToSql.EntityModel.DbContext context)
        {
            this.Context = context;
            //Entity = new LambdaToSql.EntityModel.DeleteEntity<T>(this.Context);

            string assemblyName = "LambdaToSql";
            string fullTypeName = string.Format("LambdaToSql.EntityModel.{0}.{1}`1", this.Context.SqlType.ToString(), "DeleteEntity");
            Type objType = Assembly.Load(assemblyName).GetType(fullTypeName);
            Type type = objType.MakeGenericType(typeof(T));
            Entity = (LambdaToSql.EntityModel.DeleteEntity<T>)Activator.CreateInstance(type, new object[] { this.Context });
        }

        public virtual LambdaToSql.Interface.IDeleteable<T> Where(Expression<Func<T, bool>> expression)
        {
            if (expression != null)
            {
                Expression exp = expression.Body as Expression;

                var obj = new LambdaRouter(this.Entity.Parameters);
                var str = obj.ExpressionRouter(exp);
                this.Entity.Parameters = obj.Parameters;
                if (this.Entity.Where.Length > 0)
                {
                    this.Entity.Where.Append(" and ");
                }
                this.Entity.Where.Append(obj.Result);
            }
            return this;
        }

        public virtual LambdaToSql.Interface.IDeleteable<T> Delete(T obj)
        {
            var tableName = this.Entity.TableName;
            var properties = this.Entity.Properties;

            var primaryName = this.Context.Table[tableName].PrimaryName;
            var pi = properties.Where(ex => ex.Name == primaryName).FirstOrDefault();

            object name = pi.Name;
            string value = Convert.ToString(pi.GetValue(obj, null));

            var ParaName = "@para0";
            if (this.Entity.Where.Length > 0)
            {
                this.Entity.Where.Append(" and ");
            }
            this.Entity.Where.Append(primaryName + " = " + ParaName);
            this.Entity.Parameters.Add(new LambdaToSql.EntityModel.DataParameter(ParaName, value));

            return this;
        }

        public virtual int ExecuteNonQuery()
        {
            var DbHelper = this.Context.DbHelper;

            var i = DbHelper.ExecuteNonQuery(this.Entity.SqlStr, this.Entity.Parameters.ToArray());

            return i;
        }

        public virtual LambdaToSql.EntityModel.Result<int> ExecuteNonQuery(bool debug)
        {
            var sw = new Stopwatch();
            sw.Start();

            var i = this.ExecuteNonQuery();

            var runTime = sw.ElapsedMilliseconds;
            sw.Stop();

            var values = JsonConvert.SerializeObject(this.Entity.Parameters.Select(ex => new { ex.Value, ex.Name }).ToList());
            var result = new LambdaToSql.EntityModel.Result<int>()
            {
                Data = i,
                ResultValue = i,
                Method = "ExecuteNonQuery",
                RunTime = (int)runTime,
                DeBug = string.Format("执行语句:{0}<br />值:{1}<br />执行时间:{2}ms<br />执行结果:{3}", this.Entity.SqlStr, values, runTime, i)
            };
            return result;
        }
    }
}
